package com.blog.personalblog.controller;

import com.blog.personalblog.DTO.UserDto;
import com.blog.personalblog.VO.UserVo;
import com.blog.personalblog.entity.User;
import com.blog.personalblog.entity.response.ReturnCode;
import com.blog.personalblog.service.Impl.UserServiceImpl;
import com.blog.personalblog.service.UserService;
import com.blog.personalblog.util.JsonResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.concurrent.CopyOnWriteArrayList;
@Tag(name = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {
    private static final org.apache.logging.log4j.Logger Logger = LogManager.getLogger(UserController.class);
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 查询所有用户信息
     */
    @Operation(summary = "查询所有用户信息",description = "查询所有用户信息")
    @PostMapping("/getAllUser")

    public JsonResult<List<UserVo>> getAllUser(){
        Logger.info("Enter UserController getAllUser");
        try {
            var res = userService.getAllUser();
            if (res.getReturnCode() != ReturnCode.Ok){
                return JsonResult.error(res.getMsg());
            }
            List<User> users = res.getData();
            List<UserVo> userVoList= new CopyOnWriteArrayList<>();
            users.parallelStream().forEach(user -> {
                try {
                   UserVo userVo =  ConvertToUserVo(user);
                   userVoList.add(userVo);
                }catch (Exception e){
                    Logger.error("ConvertToUserVo failed");
                    throw e;
                }
            });
            return JsonResult.success(userVoList);
        }catch (Exception e){
            Logger.error("UserController getAllUser failed");
            return JsonResult.error();
        }finally {
            Logger.info("Leave UserController getAllUser");
        }
    }

    @Operation(summary = "添加用户")
    @PostMapping("/create")
    public JsonResult<Boolean> createUser(@RequestBody @Valid UserDto user){
        Logger.info("Enter UserController creatUser");
        try {
            var res = userService.createUser(user);
            if (res.getReturnCode() != ReturnCode.Ok){
                return JsonResult.error(res.getData(),res.getMsg());
            }

            return JsonResult.success(true);
        }catch (Exception e){
            Logger.error("UserController creatUser failed");
            return JsonResult.error();
        }finally {
            Logger.info("Leave UserController creatUser");
        }
    }

    /**
     *
     * 修改用户
     * @return
     */
    @Operation(summary = "修改用户")
    @PostMapping("/update")
    public JsonResult<Boolean> updateUser(@RequestBody @Valid UserDto user){
        Logger.info("Enter UserController updateUser");
        try {
            var res = userService.updateUser(user);
            if (res.getReturnCode() != ReturnCode.Ok){
                return JsonResult.error(res.getData(),res.getMsg());
            }
            return JsonResult.success(res.getData());
        }catch (Exception e){
            Logger.error("UserController updateUser failed");
            return JsonResult.error();
        }finally {
            Logger.info("Leave UserController updateUser");
        }
    }

    /**
     * 删除
     * @return
     */
    @Operation(summary = "删除用户")
    @PostMapping("/delete/{id}")
    public JsonResult<Boolean> deleteUser(@PathVariable(value = "id") int id){
        Logger.info("Enter UserController deleteUser");
        try {
            var res = userService.deleteUser(id);
            if (res.getReturnCode() != ReturnCode.Ok){
                return JsonResult.error(res.getData(),res.getMsg());
            }
            return JsonResult.success(res.getData());
        }catch (Exception e){
            Logger.error("UserController deleteUser failed");
            return JsonResult.error();
        }finally {
            Logger.info("Leave UserController deleteUser");
        }
    }
    private static UserVo ConvertToUserVo(User user){
        if (user == null) return null;
        UserVo userVo = new UserVo();
        userVo.setId(user.getId());
        userVo.setUserName(user.getUserName());
        userVo.setEmail(user.getEmail());
        userVo.setNickname(user.getNickname());
        userVo.setPhone(user.getPhone());
        userVo.setLastLoginTime(user.getLastLoginTime());

        return userVo;
    }
}
